package com.tensquare.usercrawler.pipeline;

import java.io.IOException;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.tensquare.dto.User;
import com.tensquare.usercrawler.client.UserClient;
import com.tensquare.util.DownloadUtil;
import com.tensquare.util.IdWorker;

import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

/**
 * 用户入库
 * @author Johnny.Chen
 *
 */
@Component
public class UserPipeline implements Pipeline{
	
	@Autowired
	private UserClient userClient;
	
	@Autowired
	private IdWorker idWorker;
	
	@Value("${tensquare.webmagic.savePath}")
	private String savePath;

	@Override
	public void process(ResultItems resultItems, Task task) {
		String nickName = resultItems.get("nickname");
		
		//https://static.oschina.net/uploads/user/1349/2699955_200.jpg?t=1461768696000
		String avatar = resultItems.get("avatar");
		
		String imgName = "";
		
		
		//下载图片
		if(StringUtils.isNotBlank(avatar)) {
			try {
				imgName = idWorker.nextId() + ".jpg";
				DownloadUtil.download(avatar, imgName, savePath);
			} catch (IOException e) {
				//e.printStackTrace();
				System.out.println("下载图片异常信息："+e.getMessage());
				imgName = "";
			}
		}
		
		//实例一个user
		User user = new User();
		user.setNickname(nickName);
		user.setAvatar(imgName);//设置头像
		user.setLoginname(nickName);
		userClient.add(user);
	}

	
}
